package com.xzone.material.security.authentication

import com.fasterxml.jackson.databind.ObjectMapper
import com.xzone.material.security.MyUser
import com.xzone.material.security.service.TokenService
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.MediaType
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.stereotype.Component

@Component
class MyAuthenticationSuccessHandler(val tokenService: TokenService) : AuthenticationSuccessHandler {
    override fun onAuthenticationSuccess(
        request: HttpServletRequest, response: HttpServletResponse, authentication: Authentication
    ) {
        val mapper = ObjectMapper()

        val result = HashMap<String, Any>()

        val tokenPayload = HashMap<String, Any>()
        tokenPayload["userId"] = (authentication.principal as MyUser).userId
        val jwt = tokenService.createToken(tokenPayload);

        result["jwt"] = jwt

        response.characterEncoding = Charsets.UTF_8.name()
        response.contentType = MediaType.APPLICATION_JSON_VALUE
        response.writer.write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result))
    }
}